package com.tccmeta.mapper;

import com.tccmeta.po.Meta;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @author pan
 */
public class MetaRelationDataSqlProvider {
   SQL sql = new SQL();
    /**
     * @param para 参数
     * @return SQL
     */
    public String findPage(Map<?, ?> para) {
        Meta node = (Meta) para.get("meta");
        this.getSql(node, null,null);
        return "select * from ("+sql.toString()+(!StringUtils.isEmpty(node.getExpression())?" where "+node.getExpression():"")+") as a";
    }

    /**
     * @param node 参数
     * @return SQL
     */
    public String findAll(Meta node) {
        this.getSql(node, null,null);
        return sql.toString() +(!StringUtils.isEmpty(node.getExpression())?" where "+node.getExpression():"");
    }

    /**
     * ${'n'+condition.oneDimensional}.id = ${'n'+item.oneDimensional}.related_meta_id
     *
     * @param node 节点
     */
    public void getSql(Meta node, Meta root,String rootOneDimensional) {
        if(root==null){
            rootOneDimensional = "";
        }
        String childOneDimensional =rootOneDimensional+node.getOneDimensional();
        String nodeOneDimensional= node.getOneDimensional()+"";
        String selectId = "n" +childOneDimensional+ ".id as id" +childOneDimensional;
        String selectData = "n" +childOneDimensional+ ".data as data" +childOneDimensional;
        String selectAlias = "n" + childOneDimensional+ ".alias as alias" + childOneDimensional;
        String selectType = "n" + childOneDimensional+ ".type as type" + childOneDimensional;
        sql.SELECT(selectId);
        sql.SELECT(selectData);
        sql.SELECT(selectAlias);
        sql.SELECT(selectType);
        String t = "(SELECT md.*,mr.related_meta_id FROM meta md LEFT JOIN meta_relation mr ON mr.meta_id =md.id WHERE md.one_dimensional = "+nodeOneDimensional+" ) AS n%replace%";
        String table = t.replaceAll("%replace%", childOneDimensional);
        if (root == null) {
            sql.FROM(table);
        } else {
            sql.LEFT_OUTER_JOIN(table + " on n" + rootOneDimensional + ".id = n" + childOneDimensional+ ".related_meta_id");
        }
        List<Meta> childes = node.getRelations();
        if (childes != null && childes.size() > 0) {
            for (Meta item : childes) {
                this.getSql(item, node,childOneDimensional);
            }
        }
    }

}
